package com.atguigu.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsConfigurationSource;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.server.ServerWebExchange;

//自定义的 gateway的 filter
//实现功能：为了解决跨域问题，添加一个Filter：在所有请求的响应中，加上一些信息。通知浏览器允许跨域
@Configuration
public class GulimallCorsConfiguration {

    //CorsWebFilter：Spring框架提供的，专门用于解决跨域问题的Filter
    @Bean
    public CorsWebFilter corsWebFilter(){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();

        //1.配置跨域
        corsConfiguration.addAllowedHeader("*"); // 任意请求头
        corsConfiguration.addAllowedMethod("*"); // 任意请求方式
        corsConfiguration.addAllowedOrigin("*"); // 任意请求来源
        corsConfiguration.setAllowCredentials(true); // 允许携带cookie信息

        source.registerCorsConfiguration("/**",corsConfiguration); // 任意路径进行跨域配置
        return new CorsWebFilter(source);
    }
}
